<template>
    <div class="panel" v-if="checkPermission('B_0341')">
        <div class="panel-hd" v-loading.fullscreen.lock="loading" element-loading-text="拼命导出中">
            <span>
                <span>面板：</span>
                <el-select v-model="searchParam.useEntryPanelCode" @change="changePanel" style="width: 100px" placeholder="请选择面板" size="mini">
                    <el-option v-for="item in panelDataSource" :key="item.key" :label="item.panelCode + ' ' + item.panelName" :value="item.panelCode">
                    </el-option>
                </el-select>
            </span>
            <span>
                <span>模块：</span>
                <el-select
                    v-model="searchParam.moduleCodes"
                    style="width: 170px"
                    size="mini"
                    filterable
                    multiple
                    collapse-tags
                    clearable
                    placeholder="请选择"
                >
                    <el-option
                        v-for="item in allModuleData"
                        :key="item.moduleCode"
                        :label="item.moduleCode + ' ' + item.moduleName"
                        :value="item.moduleCode"
                        :title="item.moduleName"
                    >
                    </el-option>
                </el-select>
            </span>
            <span>
                <span>产品组：</span>
                <el-select v-model="searchParam.fundGrCode" style="width: 170px" size="mini" multiple collapse-tags placeholder="请选择">
                    <el-option v-for="item in fundGroup" :key="item.dictKey" :label="item.dictKey + ' ' + item.dictKeyName" :value="item.dictKey">
                    </el-option>
                </el-select>
            </span>
            <span>
                <span>产品：</span>
                <el-select
                    v-model="searchParam.fundCodes"
                    @visible-change="handleVisibleChange"
                    :filter-method="getFundInfoList"
                    :loading="stockReportState"
                    style="width: 170px"
                    size="mini"
                    filterable
                    multiple
                    collapse-tags
                    placeholder="请选择"
                >
                    <el-option v-for="item in fundInfo" :key="item.dictKey" :label="item.dictKey + ' ' + item.dictKeyName" :value="item.dictKey">
                    </el-option>
                </el-select>
            </span>

            <span>
                <!-- <el-button
                    @click="
                        () => {
                            webSocket.close();
                        }
                    "
                >
                    dianji
                </el-button> -->
                <el-button size="mini" @click="resetData">重置</el-button>
                <el-button type="primary" size="mini" @click="changePanelSearch">查询</el-button>
                <el-button type="primary" size="mini" @click="loadPanel">导出</el-button>
                <el-button type="primary" size="mini" @click="layoutDialog = true">布局设置</el-button>
                <el-button type="primary" @click="handleAgainConnect" size="mini" v-show="showAgainConnect">重新连接</el-button>
            </span>
        </div>
        <div style="text-align: right">
            <el-popover placement="bottom" width="80" trigger="click" v-model="thresoldTypeVisible">
                <vxe-table
                    :data="ThresholdTypeDict"
                    @checkbox-all="thresholdTypeSelectChange"
                    @checkbox-change="thresholdTypeSelectChange"
                    style="width: 100%"
                    border
                    ref="multipleTable"
                    show-header-overflow
                    show-overflow
                    :auto-resize="true"
                    resizable
                >
                    <vxe-column type="checkbox" width="40"> </vxe-column>
                    <vxe-column field="dictKeyName" title="触警状态"> </vxe-column>
                </vxe-table>
                <i
                    :class="{ 'el-icon-s-unfold': thresoldTypeVisible, 'el-icon-s-fold': !thresoldTypeVisible }"
                    style="font-size: 22px; line-height: 30px; cursor: pointer; margin-right: 10px"
                    slot="reference"
                ></i>
            </el-popover>
        </div>

        <div class="panel-body">
            <div class="panel-subs">
                <div class="panel-subs-body">
                    <div
                        style="display: flex"
                        v-for="pItem in panelDetailDataSource"
                        v-show="!hiddenPanelList.includes(pItem.moduleCode)"
                        :key="`key-${pItem.moduleCode}`"
                    >
                        <div class="left-panel">
                            <trigger-screen
                                :ref="`triggerScreen-${pItem.moduleCode}`"
                                :pItem="pItem"
                                :totalDynamicColumn="dynamicColumns.MONITOR_COUNT.showFieldColumns"
                                :searchParam="searchParam"
                                :isFullScreen="isFullScreen"
                                :thresholdTypeKeys="thresholdTypeKeys"
                                :panelDetailDataSource="panelDetailDataSource"
                                @refresh-screen="refreshRet"
                                @openEntryResultDetail="openEntryResultDetail"
                                @onCloseTable="onCloseTable"
                                @screen-change="screenChange(arguments)"
                                :reload="reload"
                                :key="'screen' + pItem.moduleCode"
                                :monitorType="monitorType"
                            ></trigger-screen>
                        </div>
                        <div :class="['right-panel', pItem.moduleCode]">
                            <trigger-detail
                                :ref="`triggerDetail-${pItem.moduleCode}`"
                                :pItem="pItem"
                                :detailDynamicColumn="dynamicColumns.MONITOR_DETAIL.showFieldColumns"
                                :searchParam="searchParam"
                                :isFullScreen="isFullScreen"
                                :hasChangeObj="hasChangeObj"
                                :operateType="operateType"
                                @edit="editReturn"
                                @openEntryResultDetail="openEntryResultDetail"
                                @onFullScreen="onFullScreen"
                                @onCloseTable="onCloseTable"
                                :key="'detail' + pItem.moduleCode"
                                :handleUsers="handleUsers"
                                :entryGroupsDict="entryGroupsDict"
                                :reload="reload"
                                :fundInfo="fundInfo"
                            ></trigger-detail>
                        </div>
                    </div>
                    <div class="left-panel" v-show="hiddenPanelList.length" key="panel-subs-add" style="height: calc(50vh - 50px)">
                        <div class="panel-subs-body-box-hd">
                            <span>&nbsp;</span>
                        </div>
                        <div class="panel-subs-body-box-main" @click="addPanelDetailData">
                            <i class="el-icon-circle-plus-outline"></i>
                        </div>
                    </div>
                </div>
                <div class="no-data" v-if="!panelDetailDataSource.length">暂无数据</div>
            </div>
        </div>

        <yh-dialog title="添加模块" :visible.sync="panelVisible" drag>
            <el-checkbox-group v-model="panelShowData" size="mini">
                <el-checkbox
                    v-for="spItem in panelDetailDataSource"
                    :label="spItem.moduleCode"
                    style="display: block; padding: 2px"
                    :key="spItem.moduleCode"
                    :title="spItem.moduleName"
                >
                    {{ spItem.moduleName }}
                </el-checkbox>
            </el-checkbox-group>
            <span slot="footer" class="dialog-footer">
                <el-button @click="panelVisible = false">取 消</el-button>
                <el-button type="primary" @click="closePanelDetailData">确 定</el-button>
            </span>
        </yh-dialog>

        <div class="panel-subs-popup">
            <ItemRealTimeMonitoringEntryTable v-if="entryVisible" :entry-info="entryInfo" @on-submit="detailTableReturn" />
        </div>

        <RiskMonitorTableLayout
            :totalField="dynamicColumns.MONITOR_COUNT"
            :detailField="dynamicColumns.MONITOR_DETAIL"
            title="页面布局"
            :visible.sync="layoutDialog"
            @on-submit="onSubmit"
        />
    </div>
</template>

<script lang="ts">
import { Component, Vue, Watch } from 'vue-property-decorator';

import DictionConstUtil from '@/utils/diction-const-util';
import { getUser } from '@/utils/user-util';
import { checkPermission, getConfigItem, numberFormat, sortBy, StringToBase64, timeFormat } from '@/utils/tools';
import XEUtils from 'xe-utils';
import { downLoadFile } from '@/utils/request';
import ItemRealTimeMonitoringEntryTable from './item-real-time-monitoring/item-real-time-monitoring-entry-table.vue';
import RiskMonitorTableLayout from './item-real-time-monitoring/risk-monitor-table-layout.vue';
import { getEntryResult, getModuleByPanelCode, getModuleEnableEntry, getModuleHabit, getUserPanel, updateModuleHabit } from './api';
import StatusTag from '@/pages/risk-measure/components/status-tag.vue';
import TriggerScreen from './item-real-time-monitoring/trigger-screen.vue';
import TriggerDetail from './item-real-time-monitoring/trigger-detail.vue';
import { getTableLayout } from '@/common/api/commonApi';

@Component({
    name: 'ItemRealTimeMonitoring',
    components: {
        ItemRealTimeMonitoringEntryTable,
        StatusTag,
        TriggerScreen,
        TriggerDetail,
        RiskMonitorTableLayout,
    },
})
export default class ItemRealTimeMonitoring extends Vue {
    BASE_URL_WS = getConfigItem('BASE_URL_WS');
    checkPermission = checkPermission;

    private loading: boolean = false;
    private layoutDialog: boolean = false; // 布局显示值

    private dynamicColumns = {
        MONITOR_COUNT: {
            columns: [
                //{ name: '处理状态', val: 'handleStatus', minWidth: 105, showOverflowTooltip: true, sortable: 'custom', fixedable: true },
                { name: '条目编号', val: 'entryCode', minWidth: 105, showOverflowTooltip: true, sortable: 'custom', fixedable: true },
                { name: '条目名称', val: 'entryName', minWidth: 105, showOverflowTooltip: true, sortable: 'custom', fixedable: true },
                { name: '计算时间', val: 'calculateTime', minWidth: 105, showOverflowTooltip: true, sortable: 'custom', fixedable: false },
                { name: '阈值', val: 'thresholdValue', minWidth: 90, showOverflowTooltip: true, sortable: 'custom', fixedable: false },
                { name: '触警状态', val: 'thresholdType', minWidth: 105, showOverflowTooltip: true, sortable: 'custom', fixedable: false },
                { name: '实际值', val: 'calculateValue', minWidth: 100, showOverflowTooltip: true, sortable: 'custom', fixedable: false },
                { name: '禁止数', val: 'prohibitNum', minWidth: 90, showOverflowTooltip: true, sortable: false, fixedable: false },
                { name: '送审数', val: 'examinationNum', minWidth: 90, showOverflowTooltip: true, sortable: false, fixedable: false },
                { name: '警告数', val: 'warningNum', minWidth: 90, showOverflowTooltip: true, sortable: false, fixedable: false },
                { name: '合规数', val: 'complianceNum', minWidth: 90, showOverflowTooltip: true, sortable: false, fixedable: false },
            ],
            selectedColumns: [],
            showFieldColumns: [],
        },
        MONITOR_DETAIL: {
            columns: [
                { name: '条目编号', val: 'entryCode', minWidth: 105, showOverflowTooltip: true, sortable: 'custom', fixedable: true },
                { name: '条目名称', val: 'entryName', minWidth: 105, showOverflowTooltip: true, sortable: 'custom', fixedable: true },
                { name: '阈值', val: 'thresholdValue', minWidth: 85, showOverflowTooltip: true, sortable: 'custom', fixedable: false },
                { name: '产品名称', val: 'fundNameSt', minWidth: 105, showOverflowTooltip: true, sortable: 'custom', fixedable: false },
                { name: '触警状态', val: 'thresholdType', minWidth: 105, showOverflowTooltip: true, sortable: 'custom', fixedable: false },
                { name: '实际值', val: 'calculateValue', minWidth: 100, showOverflowTooltip: true, sortable: 'custom', fixedable: false },
                { name: '计算逻辑', val: 'calLogic', minWidth: 105, showOverflowTooltip: true, sortable: 'custom', fixedable: false },
                { name: '证券代码', val: 'stockCodes', minWidth: 105, showOverflowTooltip: true, sortable: 'custom', fixedable: false },
                { name: '发行人', val: 'issueInfoName', minWidth: 105, showOverflowTooltip: true, sortable: 'custom', fixedable: false },
                { name: '备注信息', val: 'comment', minWidth: 140, showOverflowTooltip: true, sortable: 'custom', fixedable: false },
                { name: '处理人', val: 'userInfos', minWidth: 100, showOverflowTooltip: true, sortable: 'custom', fixedable: false },
            ],
            selectedColumns: [],
            showFieldColumns: [],
        },
    };

    private detailDynamicColumn: [];
    private totalDynamicColumn: [];

    private layoutTotalColumns: any;
    private layoutDetailColumns: any;
    // 显示重新连接
    private showAgainConnect = false;
    private operateType: string = '';

    monitorType: string[] = ['1']; // 后台监控屏计算模式

    async created() {
        if (!checkPermission('B_0341')) return;

        await getModuleHabit().then((res: any) => {
            if (res) {
                this.thresholdTypeKeys = res.habitValue;
                if (res.habitValue.includes('-1')) {
                    this.thresholdTypeKeys = [];
                } else {
                    this.thresholdTypeKeys = res.habitValue;
                }
            } else {
                this.thresholdTypeKeys = ['3'];
            }
        });
        console.log(this.thresholdTypeKeys, 'thresholdTypeKeys');

        // 基金组信息
        await getUserPanel().then(response => {
            // const arr = response.sort(sortBy('panelOrder', 'asc'));
            const arr = response;
            let obj0 = {panelCode: ''}
            let path = false;
            for (let i = 0; i < response.length; i++) {
                if (response[i].panelType == '2') {
                    obj0 = {...response[i]};
                    path = true;
                    break
                }
                if (i == response.length - 1) {
                    obj0 = {...response[0]}
                }
            }
            if (!path) {
                for (let i = 0; i < response.length; i++) {
                if (['1', '3'].includes(response[i].panelType) && response[i].panelCode != 'DEFAULT') {
                    obj0 = {...response[i]};
                    break
                }
                if (i == response.length - 1) {
                    obj0 = {...response[0]}
                }
            }
            }
            if (obj0) {
                this.searchParam.useEntryPanelCode = obj0.panelCode;
            }
            console.log(this.searchParam.useEntryPanelCode, 'this.searchParam.useEntryPanelCode');

            let panelDataSource = response || [];
            panelDataSource.forEach(element => {
                element.key = element.panelCode;
            });
            this.panelDataSource = panelDataSource;
        });
        // 基金名称列表
        // DictionConstUtil.FNFundInfo().then(response => {
        //     this.fundInfo = response.map(item => {
        //         return { dictKey: item.fundCode, dictKeyName: item.fundNameSt };
        //     });
        // });
        this.getFundInfoList('');

        // 基金组名称列表
        DictionConstUtil.FNFundGroup().then((response: any) => {
            this.fundGroup = response.map(item => {
                return { dictKey: item.fundGroupCode, dictKeyName: item.fundGroupName };
            });
        });
        // 模块
        this.$axios.get('/entry/subscribe/all/module/user').then((response: any) => {
            this.moduleAll = response;
        });

        // 处理人下拉列表
        this.$axios.post('/instruction/user/select').then((res: any) => {
            this.handleUsers = res;
        });

        // 条目组下拉框
        this.$axios.get('/entry/group/list').then((res: any) => {
            this.entryGroupsDict = res || [];
        });

        // 初始化
        this.initWebsocketConnect();

        this.monitorType = ((await this.getMonitorType()) as any) || ['1'];

        await this.changePanel();
    }

    mounted() {
        this.onSubmit();
    }

    @Watch('totalDynamicColumn', { deep: true })
    watchTotalDynamicColumn() {
        console.log('totalDynamicColumn');
    }

    private ThresholdTypeDict = DictionConstUtil.PojoToList(DictionConstUtil.ThresholdType).filter(item => item.dictKey != '4');

    thresholdTypeKeys: any[] = ['3']; // 触警状态keys

    private panelDataSource = []; // 面板下拉

    private fundInfo = []; // 基金名称列表

    private fundGroup = []; // 基金组名称列表

    private moduleAll = []; // 所有模块列表

    private allModuleData: any[] = []; // 可选所有模块

    // hasSelectModuleData: any[] = []; // 已选择模块

    handleUsers: any[] = []; // 处理人

    thresoldTypeVisible: boolean = false;

    // 搜索条件
    private searchParam = {
        useEntryPanelCode: 'DEFAULT',
        fundGrCode: [],
        fundCodes: [],
        moduleCodes: [],
    };

    // 实际值明细
    private entryInfo = {
        title: '',
        entryCode: '',
        fundCode: '',
        fundNameSt: '',
        moduleCode: '',
        isModule: true,
        row: {},
        searchParam: {},
    };

    // 用作子组件刷新用
    private reload: number = 1;

    private isFullScreen = null; // 表格放大状态

    private hiddenPanelList = []; // 隐藏的面板列表

    private panelVisible = false; // 添加模块弹框显示

    private panelShowData = []; // 弹窗 - 下面表格布局

    private panelDetailDataSource = []; // 所有模板表格数据

    private entryVisible: boolean = false; // 实际值明细弹窗

    private entryGroupsDict: any[] = []; // 条目组下拉框

    hasChangeObj: any = {};

    transThresholdType: any[] = [];

    @Watch('showAgainConnect', { immediate: true, deep: true })
    watchShowAgainConnect(newData, oldData) {
        if (newData) {
            console.log('监听到WS已掉线, 自动发起心跳MSG' + XEUtils.toDateString(new Date(), 'yyyy-MM-dd hh:mm:ss'));
            this.handleAgainConnect();
        }
    }

    /**
     * 重新连接WEB-SOCKET
     */
    handleAgainConnect() {
        if (this.TimeSendMessage) {
            clearInterval(this.TimeSendMessage);
            this.TimeSendMessage = null;
        }
        try {
            this.webSocket.close();
        } catch (e) {}

        if (!this.pacemaker) {
            // 设置起搏器 用于电脑休眠唤醒后 自动重连ws
            this.pacemaker = setInterval(() => {
                if (this.showAgainConnect) {
                    this.initWebsocketConnect();
                }
            }, 1500);
        }

        this.initWebsocketConnect();
    }
    private pacemaker: any = null;

    async queryLayout(tableName, onSucess) {
        await getTableLayout(tableName).then(resList => {
            if (!resList) {
                // 新用户初始化
                this.dynamicColumns[tableName].selectedColumns = this.dynamicColumns[tableName].columns
                    .filter(item => !item.fixedable)
                    .map(item => item.val);
                this.dynamicColumns[tableName].showFieldColumns = this.dynamicColumns[tableName].columns;
            } else {
                let selectFields = JSON.parse(resList) || [];
                let showFieldColumns = this.dynamicColumns[tableName].columns.filter(item => item.fixedable);
                selectFields.forEach(col => {
                    const val = this.dynamicColumns[tableName].columns.find(item => {
                        return item.val === col;
                    });
                    if (val) {
                        showFieldColumns.push(val);
                    }
                });
                this.dynamicColumns[tableName].showFieldColumns = showFieldColumns;
                console.log('列', this.dynamicColumns[tableName].showFieldColumns);
                this.dynamicColumns[tableName].selectedColumns = selectFields;
                onSucess();
            }
        });
    }

    // 保存面板后执行查询
    onSubmit() {
        this.queryLayout('MONITOR_COUNT', () => {
            this.totalDynamicColumn = JSON.parse(JSON.stringify(this.dynamicColumns.MONITOR_COUNT.showFieldColumns));
            this.layoutTotalColumns = JSON.parse(JSON.stringify(this.dynamicColumns.MONITOR_COUNT));
        });
        this.queryLayout('MONITOR_DETAIL', () => {
            this.detailDynamicColumn = JSON.parse(JSON.stringify(this.dynamicColumns.MONITOR_DETAIL.showFieldColumns));
            this.layoutDetailColumns = JSON.parse(JSON.stringify(this.dynamicColumns.MONITOR_DETAIL));
        });
    }

    /**
     * 初始化WebSocket连接
     * 有消息来的时候触发重新查询操作，临时处理
     */
    TimeSendMessage = null;
    webSocket = null;
    initWebsocketConnect() {
        let Authentication = getUser().sessionId;
        this.webSocket = new WebSocket(this.BASE_URL_WS + '/monitor/socket/' + StringToBase64(Authentication));
        this.webSocket.onopen = e => {
            this.$notify({
                type: 'success',
                message: '连接成功',
                title: '实时风险监控服务连接成功',
            });
            this.showAgainConnect = false;

            this.webSocket.send(this.searchParam.useEntryPanelCode);
        };
        this.webSocket.onmessage = e => {
            // console.log('风险全景图 WEBSOCKET收到消息：', e);
            // if (!this.searchParam.useEntryPanelCode) {
            //     return;
            // }
            // // this.getModulesByPanelCode(searchParam.panelCode);
            // // 消息延迟5秒获取，假如5秒内推了多条消息则只获取一次
            // if (this.getDataTimeOut != null) {
            //     clearTimeout(this.getDataTimeOut);
            //     this.getDataTimeOut = null;
            // }
            // this.getDataTimeOut = setTimeout(async () => {
            //     await this.getEntryResultSimple(null, this.searchParam); //
            //     this.changePanelSearch();
            // }, 5000);
        };
        this.webSocket.onclose = e => {
            console.log('websocket 断开: ' + e.code + ' ' + e.reason + ' ' + e.wasClean);

            console.log(e, XEUtils.toDateString(new Date(), 'yyyy-MM-dd hh:mm:ss'));
            this.$notify({
                type: 'success',
                message: '实时风险监控服务已断开',
                title: '实时风险监控服务已断开',
            });
            // this.resetData();
            this.showAgainConnect = true;
        };

        // 每隔1个小时发送一次消息 确保在使用nginx的情况下不会有断连的情况，同时约定nginx后台配置超时时间超过一个小时
        this.TimeSendMessage = setInterval(() => {
            try {
                this.webSocket.send('风险全景图-发送WEBSOCKET心跳消息');
            } catch (e) {}
        }, 1000 * 60 * 5);
    }

    private beforeDestroy(): void {
        if (this.TimeSendMessage) {
            clearInterval(this.TimeSendMessage);
            this.TimeSendMessage = null;
        }

        if (this.pacemaker) {
            clearInterval(this.pacemaker);
            this.pacemaker = null;
        }

        try {
            this.webSocket.close();
        } catch (e) {}
    }

    // 重置数据
    resetData() {
        // 搜索条件
        this.searchParam = {
            useEntryPanelCode: 'DEFAULT',
            fundGrCode: [],
            fundCodes: [],
            moduleCodes: [],
        };
        this.changePanel();
    }

    // 改变面板
    async changePanel() {
        if (!this.searchParam.useEntryPanelCode) {
            this.yh_message_warn('请选择面板');
            return;
        }

        await this.getEntryResultSimple(null, this.searchParam);

        this.hiddenPanelList = [];
        // 面板数据
        this.panelDetailDataSource = [];

        // this.$nextTick(() => {
        (this.$refs.multipleTable as any).clearCheckboxRow();

        let data = [];
        this.thresholdTypeKeys.forEach(key => {
            let value1 = this.ThresholdTypeDict.find(item => item.dictKey == key);
            data.push(value1);
        });
        (this.$refs.multipleTable as any).setCheckboxRow(data, true);
        this.changePanelSearch();
        // });

        this.webSocket.send(this.searchParam.useEntryPanelCode);
    }
    timer = null;
    stockReportState: boolean = false; //

    getFundInfoList(val) {
        this.stockReportState = true;
        try {
            clearTimeout(this.timer);
        } catch (e) {}
        this.timer = setTimeout(() => {
            this.$axios
                .get('/fundInfo/list/byUser/like?fundCodeOrName=' + encodeURIComponent(val))
                .then((res: any) => {
                    this.fundInfo = res.map(item => {
                        return { dictKey: item.fundCode, dictKeyName: item.fundNameSt };
                    });
                    this.stockReportState = false;
                })
                .catch(() => {
                    this.stockReportState = false;
                });
        }, 300);
    }

    handleVisibleChange(state: boolean) {
        if (!state && !this.fundInfo.length) {
            this.getFundInfoList('');
        }
    }

    isFirst: boolean = true;

    // 查询
    async changePanelSearch() {
        if (!this.searchParam.useEntryPanelCode) {
            this.yh_message_error('面板不可为空,请选择面板!');
            return;
        }
        this.panelDetailDataSource = this.allModuleData.filter(item => this.searchParam.moduleCodes.includes(item.moduleCode));
        // this.loading = true;
        // await new Promise((resolve, reject) => {
        //     getEntryResult(this.searchParam)
        //         .then((res: any) => {
        //             // 重新进行查询
        //             this.panelDetailDataSource = this.allModuleData.filter(item => this.searchParam.moduleCodes.includes(item.moduleCode));
        //             this.loading = false;
        //             resolve(res);
        //         })
        //         .catch(e => {
        //             reject(e);
        //             console.log(e, '查询错误');
        //             this.loading = false;
        //         });
        // });
        if (this.isFirst) {
            this.isFirst = false;
        } else {
            this.reload++;
        }
    }

    /**
     * 获取后台监控屏计算模式配置
     */
    getMonitorType() {
        return new Promise((resolve, reject) => {
            this.$axios({ url: '/panorama/query/monitor/type', method: 'post' }).then(res => {
                resolve(res);
            });
        });
    }

    // 导出面板
    loadPanel(): void {
        if (!this.searchParam.useEntryPanelCode) {
            this.yh_message_info('面板不可为空！');
            return;
        }
        this.loading = true;
        downLoadFile({
            url: '/panorama/export/excel',
            method: 'post',
            data: {
                ...this.searchParam,
                thresholdTypes: this.thresholdTypeKeys,
            },
        })
            .then(() => {
                this.loading = false;
            })
            .catch(() => {
                this.loading = false;
            });
    }

    // 获取条目的简要结果信息
    private getEntryResultSimple(resultIds, searchParam) {
        return new Promise((resolve, reject) => {
            getModuleByPanelCode(this.searchParam.useEntryPanelCode)
                .then((res: any) => {
                    const response = res || [];
                    const keys = XEUtils.map(response, item => item.moduleCode);
                    this.searchParam.moduleCodes = keys;

                    this.allModuleData = response.map((item, index) => {
                        return {
                            ...item,
                            index: index,
                        };
                    });

                    resolve(res);
                })
                .catch(err => {
                    reject(err);
                });
        });
    }

    // 全屏功能
    onFullScreen(code) {
        const dom = document.querySelector('.right-panel.' + code);
        this.isFullScreen = this.isFullScreen ? null : code;
        if (dom) {
            dom.classList.toggle('full-screen');
        }
    }

    // 关闭表格
    onCloseTable(code) {
        if (this.isFullScreen !== null) {
            this.onFullScreen(code);
        }
        this.isFullScreen = null;
        this.hiddenPanelList.push(code);
    }

    // 监控屏勾选变化
    screenChange(args: any) {
        this.hasChangeObj = args[0];
        this.hasChangeObj.operateType = args[1];
        // 获取系统日志类型 autoRefresh:自动刷新请求，为空默认为人为请求
        this.operateType = args[1];
    }
    // screenChange(obj) {
    //     this.hasChangeObj = obj;
    // }

    // 添加面板
    addPanelDetailData() {
        this.panelShowData = this.panelDetailDataSource.filter(item => !this.hiddenPanelList.includes(item.moduleCode)).map(item => item.moduleCode);
        this.panelVisible = true;
    }

    // 关闭面板(添加)
    closePanelDetailData() {
        this.hiddenPanelList = this.panelDetailDataSource.filter(item => !this.panelShowData.includes(item.moduleCode)).map(item => item.moduleCode);
        this.panelVisible = false;
    }

    // paging: any = {};

    // 实际值明细
    detailTableReturn(curPage: number) {
        this.entryVisible = false;
        // let key = this.entryInfo.entryCode + this.entryInfo.moduleCode;
        // this.$set(this.paging, key, curPage);
    }

    // 备注信息编辑
    editReturn(moduleCode) {
        // 刷新兄弟组件的查询
        console.log(this.$refs['triggerScreen-' + moduleCode], this.$refs['triggerScreen-' + moduleCode][0]);
        this.$refs['triggerScreen-' + moduleCode][0].submitSearchModule();
    }

    async refreshRet(moduleCode) {
        console.log(moduleCode);
        this.$refs['triggerDetail-' + moduleCode][0].submitSearchModule();
    }

    // 打开弹窗表格
    openEntryResultDetail(obj) {
        this.entryVisible = true;
        let row = obj.row;
        let moduleCode = obj.pItem['moduleCode'];
        let moduleName = obj.pItem['moduleName'];
        this.entryInfo = {
            title: moduleName,
            entryCode: row.entryCode,
            fundCode: row.fundCode,
            fundNameSt: row.fundNameSt || '',
            moduleCode: moduleCode,
            isModule: false,
            row: JSON.parse(JSON.stringify(row)),
            searchParam: this.searchParam,
        };
        if (obj.type == 'module') {
            this.entryInfo.isModule = true;
        } else {
            this.entryInfo.isModule = false;
        }
    }

    // 触警状态改变
    thresholdTypeSelectChange({ selection }) {
        let values = selection;
        this.thresholdTypeKeys = XEUtils.map(values, item => item.dictKey);
        this.changePanelSearch();
        let keys = this.thresholdTypeKeys.length > 0 ? this.thresholdTypeKeys : [-1];
        updateModuleHabit(keys);
    }
}
</script>

<style lang="scss" scoped>
.panel {
    min-width: 1200px;
    height: 100%;
    .panel-hd {
        padding: 5px;

        > span {
            display: inline-block;
            margin: 5px;

            &:last-child {
                margin-right: 0;
            }

            & /deep/ .el-select__tags {
                flex-wrap: nowrap;

                .el-tag.el-tag--info {
                    display: flex;
                    align-items: center;

                    .el-select__tags-text {
                        display: block;
                        font-size: 12px;
                        max-width: 80px;
                        white-space: nowrap;
                        overflow: hidden;
                        text-overflow: ellipsis;
                    }
                }
            }
        }
    }

    .panel-subs {
        height: calc(100vh - 129px);
        background-color: #fff;
        .panel-subs-hd {
            position: relative;
            padding: 0 20px;
            line-height: 48px;
            font-size: 20px;
            font-weight: bold;
            border-bottom: 2px solid #808080;
            border-top: 1px solid #808080;

            // .panel-subs-hd-r {
            //     position: absolute;
            //     right: 10px;
            //     bottom: 0;
            //     display: flex;
            //     justify-content: space-between;
            //     border: 1px solid #595959;
            //     border-radius: 5px;
            //     padding: 10px 8px;

            //     .panel-subs-hd-r-line {
            //         flex-shrink: 0;
            //         width: 2px;
            //         height: 26px;
            //         background-color: #000;
            //         margin: 0 10px;
            //     }
            // }
        }

        .panel-subs-body {
            max-height: 100%;

            overflow: auto;
            background-color: #e8e8e8;

            // .panel-subs-body-wrap {
            //     display: flex;
            //     flex-wrap: wrap;
            //     padding: 10px 0 0 10px;
            //     min-width: 998px;
            // }
            .left-panel {
                min-width: 320px;
                width: 45%;
                // height: 260px;
                margin: 6px 3px 3px 6px;
                border: 1px solid #808080;
                background-color: #fff;
            }

            .right-panel {
                flex-shrink: 0;
                flex-grow: 1;
                // height: 260px;
                margin: 6px 3px 3px 6px;
                border: 1px solid #808080;
                background-color: #fff;
                min-width: 320px;
                width: calc(55% - 20px);

                &.full-screen {
                    position: fixed;
                    top: 0;
                    left: 0;
                    width: 100% !important;
                    height: 100% !important;
                    margin: 2px 0px 0px 0px !important;
                    max-width: none !important;
                    min-width: auto !important;
                    z-index: 100;
                }
            }
        }

        .no-data {
            height: calc(100vh - 90px);
            color: grey;
            font-size: 18px;
            text-align: center;
            line-height: calc(100vh - 90px);
            user-select: none;
        }
    }
    /deep/ .el-checkbox__label {
        max-width: 100%;
        overflow: hidden;
        text-overflow: ellipsis;
        vertical-align: bottom;
    }
}
</style>

<style lang="scss">
.el-select-dropdown__item {
    padding: 0 35px 0 20px;
    max-width: 250px;
}

.panel-subs-body-box-hd {
    // position: relative;
    line-height: 40px;
    height: 40px;
    // text-align: center;
    display: flex;
    justify-content: space-between;
    border-bottom: 1px solid #c8c8c8;
    .hd {
        display: inline-block;
        width: calc(100% - 320px);
        .body-box-hd-span {
            margin: auto;
            display: block;
            width: 100%;
            white-space: nowrap;
            text-overflow: ellipsis;
            overflow: hidden;
            text-align: center;
        }
    }
    .panel-subs-body-box-icon {
        // position: absolute;
        // right: 0;
        // top: 0;
        display: flex;
        align-items: center;

        // float: right;
        // text-align: right;

        > i {
            margin-left: 6px;
            margin-right: 10px;
            font-size: 22px;
            line-height: 30px;
            cursor: pointer;
        }
    }
}
.panel-subs-body-box-main {
    cursor: pointer;
    // height: 100%;
    .el-icon-circle-plus-outline {
        font-size: 40px;
        margin: 0 auto;
        display: block;
        text-align: center;
        padding-top: calc(25vh - 60px);
    }
}
/deep/ .el-popover {
    padding: 6px !important;
}
</style>
